﻿using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
using System.Security.Claims;

namespace EMall.AuthServer
{
    public class IdentityServerUserClaimsPrincipalFactory : UserClaimsPrincipalFactory<User>
    {
        public IdentityServerUserClaimsPrincipalFactory(UserManager<User> userManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, optionsAccessor)
        {
        }
        protected override async Task<ClaimsIdentity> GenerateClaimsAsync(User user)
        {
            var id = new ClaimsIdentity("Identity.Application", Options.ClaimsIdentity.UserNameClaimType, Options.ClaimsIdentity.RoleClaimType);
            id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, user.Id.ToString()));
            id.AddClaim(new Claim("username", user.UserName));
            id.AddClaim(new Claim("name", user.Name));
            id.AddClaim(new Claim("avatar", user.Avatar));
            if (UserManager.SupportsUserEmail)
            {
                id.AddClaim(new Claim(Options.ClaimsIdentity.EmailClaimType,user.Email));
            }
            if (UserManager.SupportsUserSecurityStamp)
            {
                ClaimsIdentity claimsIdentity = id;
                claimsIdentity.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType, await UserManager.GetSecurityStampAsync(user).ConfigureAwait(continueOnCapturedContext: false)));
            }
            if (UserManager.SupportsUserClaim)
            {
                ClaimsIdentity claimsIdentity = id;
                claimsIdentity.AddClaims(await UserManager.GetClaimsAsync(user).ConfigureAwait(continueOnCapturedContext: false));
            }
            return id;
        }
    }
}
